<?php
/**
 * Created by PhpStorm.
 * User: mojie126
 * Date: 2017/7/4 0004
 * Time: 下午 14:55
 */

namespace app\index\controller;


use app\common\download;
use Bhutanio\BEncode\BEncode;

class DownloadController extends Base
{
	public function dl($type, $id, $uuid)
	{
		$db = getTorrentDB($type);
		$where = [
			"id" => ["=", $id],
			"display" => ["=", "0"],
			"status" => ["=", "0"]
		];

		$res1 = db($db)->where($where)->field(["maintitle", "torrentpath"])->find();
		$res2 = db("users")->where("uuid", $uuid)->find();
		if ($res1 && $res2) {
			$torrentfile = ROOT_PATH . "public" . DS . "torrents" . DS . $res1['torrentpath'];
			$torrentname = "[" . APP_NAME . "]." . $res1['maintitle'] . ".torrent";
			$bencode = new BEncode();
			$dict = $bencode->bdecode_file($torrentfile);
			if (empty(TRACKER)) {
				$dict['announce'] = getWebURL() . "/announce/$uuid";
			} else {
				$dict['announce'] = TRACKER . "announce/$uuid";
			}
			if (file_exists($torrentfile)) {
				print($bencode->bencode($dict));
				download::downloadFile($torrentfile, $torrentname);
			} else {
				$this->error("文件找不到啦！（｡◕ˇ＿ˇ◕｡）", "/$db/id/$id");
			}
		} else {
			$this->error("也不知道怎么回事儿，就想报个错，主要还是没找到相关种子了啦╰(￣▽￣)╮", "/index/$db");
		}
	}
}